<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\VipOrder;
use think\Db;
use think\Log;
/**
 * 支付回调接口
 * @ApiInternal
 */
class Payment extends Api
{
    protected $noNeedLogin = ['notifyVip', 'notifyGoods', 'notifyTravel', 'notifyService', 'fakePayNotify']; // 将 fakePayNotify 添加到无需登录列表
    protected $noNeedRight = '*';
    
    /**
     * 会员订单支付回调
     */
    public function notifyVip()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        
        $data = $pay->verify();
        
        $order = VipOrder::getByOrderNo($data['out_trade_no']);
        if ($order && $order->status == VipOrder::STATUS_UNPAID) {
            Db::startTrans();
            try {
                // 更新订单状态
                $order->status = VipOrder::STATUS_PAID;
                $order->pay_time = time();
                $order->save();
                
                // 更新用户会员时间
                $user = \app\common\model\User::get($order->user_id);
                if($user->vip_expire_time > time()){
                    $user->vip_expire_time = strtotime(date('Y-m-d H:i:s', $user->vip_expire_time), '+1 year');
                }else{
                    $user->vip_expire_time = strtotime('+1 year');
                }
                $user->save();

                // 获取会员配置信息
                $vipConfig = \app\common\model\VipConfig::get(1);
                if ($vipConfig && $vipConfig->voucher_times > 0) {
                    // 生成代金券记录
                    for ($i = 0; $i < $vipConfig->voucher_times; $i++) {
                        \app\common\model\UserVoucher::create([
                            'user_id' => $order->user_id,
                            'vip_order_id' => $order->id,
                            'teacher_ids' => $vipConfig->teacher_ids,
                            'status' => 0, // 0=未使用
                            'expire_time' => $order->expire_time,
                            'createtime' => time()
                        ]);
                    }
                }
                
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order->user_id,
                    'type' => 'vip',
                    'title' => '下单成功',
                    'content' => "感谢您的信任，您的会员已开通，会员到期时间为" . date('Y-m-d H:i:s', $order->expire_time),
                    'order_id' => $order->id,
                    'order_no' => $order->order_no
                ]);
                
                // 记录用户消费记录
                Db::name('user_consume_log')->insert([
                    'user_id' => $order->user_id,
                    'type' => 'vip',
                    'target_id' => 1,
                    'target_title' => '会员',
                    'amount' => -$order->amount,
                    'createtime' => time()
                ]);
                
                Db::commit();
                echo $pay->success();
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                Log::error("会员订单支付回调处理失败: " . $e->getMessage());
                echo $pay->fail();
            }
        }
        
        
    }
    
    /**
     * 商品订单支付回调
     */
    public function notifyGoods()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        
        $data = $pay->verify();
        
        $order = \app\common\model\Order::where([
            'order_no' => $data['out_trade_no'],
            'status' => 0 // 待支付状态
        ])->find();
        
        if ($order) {
            Db::startTrans();
            try {
                // 更新订单状态为已支付
                $order->status = 1;
                $order->pay_time = time();
                $order->pay_type = $paytype;
                $order->transaction_id = $data['transaction_id'] ?? '';
                $order->save();
                
                // 更新商品销量
                foreach ($order->items as $item) {
                    \app\common\model\Goods::where('id', $item->goods_id)
                        ->setInc('sales', $item->quantity);
                }
                
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order->user_id,
                    'type' => 'goods',
                    'title' => '下单成功',
                    'content' => "感谢您的信任，您购买的【{$order->items[0]->goods->title}】已下单成功，订单将在48小时内发货，请及时关注物流变化",
                    'order_id' => $order->id,
                    'order_no' => $order->order_no
                ]);
                
                // 记录用户消费记录
                Db::name('user_consume_log')->insert([
                    'user_id' => $order->user_id,
                    'type' => 'goods',
                    'target_id' => $order->items[0]->goods_id,
                    'target_title' => $order->items[0]->goods->title,
                    'amount' => -$order->order_amount,
                    'createtime' => time()
                ]);
                
                Db::commit();
                echo $pay->success();
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                Log::error("订单支付回调处理失败: " . $e->getMessage());
                echo $pay->fail();
            }
        }
        
        
    }
    
    /**
     * 文旅订单支付回调
     */
    public function notifyTravel()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        
        $data = $pay->verify();
        
        $order = \app\common\model\TravelOrder::where([
            'order_no' => $data['out_trade_no'],
            'status' => \app\common\model\TravelOrder::STATUS_UNPAID
        ])->find();
        
        if ($order) {
            Db::startTrans();
            try {
                // 更新订单状态为已支付
                $order->status = \app\common\model\TravelOrder::STATUS_FINISH;
                $order->pay_time = time();
                $order->complete_time = time();
                $order->pay_type = $paytype;
                $order->transaction_id = $data['transaction_id'] ?? '';
                $order->save();
                
                // 更新文旅信息销量
                \app\common\model\Travel::where('id', $order->travel_id)
                    ->setInc('sales', $order->num);
                
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order->user_id,
                    'type' => 'travel',
                    'title' => '下单成功',
                    'content' => "感谢您的信任，您购买的【{$order->title}】已下单成功",
                    'order_id' => $order->id,
                    'order_no' => $order->order_no
                ]);
                
                // 记录用户消费记录
                Db::name('user_consume_log')->insert([
                    'user_id' => $order->user_id,
                    'type' => 'travel',
                    'target_id' => $order->travel_id,
                    'target_title' => $order->title,
                    'amount' => -$order->price,
                    'createtime' => time()
                ]);
                
                Db::commit();
                echo $pay->success();
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                Log::error("文旅订单支付回调处理失败: " . $e->getMessage());
                echo $pay->fail();
            }
        }
        
    }
    
    /**
     * 服务订单支付回调
     */
    public function notifyService()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        
        $data = $pay->verify();
        
        $order = Db::name('service_order')->where([
            'order_no' => $data['out_trade_no'],
            'status' => 0 // 待支付状态
        ])->find();
        $service = \app\common\model\Service::where('id', $order['service_id'])->find();
        if ($order) {
            Db::startTrans();
            try {
                // 更新订单状态为已支付
                $result = Db::name('service_order')->where('id', $order['id'])->update([
                    'status' => 1, // 已支付
                    'pay_time' => time(),
                    'updatetime' => time(),
                    'transaction_id' => $data['transaction_id'] ?? '',
                    'pay_type' => $paytype
                ]);
                
                if(!$result) {
                    throw new \Exception('更新订单状态失败');
                }
                
                // 给老师加余额
                // $result = Db::name('user')->where('id', $order['teacher_id'])->setInc('money', $order['amount']);
                // if(!$result) {
                //     throw new \Exception('更新老师余额失败');
                // }
                
                // // 记录老师资金变动日志
                // $result = Db::name('user_money_log')->insert([
                //     'user_id' => $order['teacher_id'],
                //     'money' => $order['amount'],
                //     'before' => Db::name('user')->where('id', $order['teacher_id'])->value('money') - $order['amount'],
                //     'after' => Db::name('user')->where('id', $order['teacher_id'])->value('money'),
                //     'memo' => '服务单号：'. $order['order_no'],
                //     'type' => 'service_income',
                //     'service_order_id' => $order['id'],
                //     'createtime' => time()
                // ]);
                
                if(!$result) {
                    throw new \Exception('记录资金日志失败');
                }
                
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order['user_id'],
                    'type' => 'service',
                    'title' => '下单成功',
                    'content' => "感谢您的信任，您购买的【{$service['name']}】服务已下单成功，请及时和老师联系",
                    'order_id' => $order['id'],
                    'order_no' => $order['order_no']
                ]);
                
                // 记录老师收益记录
                Db::name('user_consume_log')->insert([
                    'user_id' => $order['teacher_id'],
                    'type' => 'service',
                    'target_id' => $order['id'],
                    'target_title' => \app\common\model\User::where('id', $order['user_id'])->value('username') . '下单了' . $service['name'] . '服务',
                    'amount' => $order['amount'],
                    'createtime' => time()
                ]);
                // 记录用户消费记录
                Db::name('user_consume_log')->insert([
                    'user_id' => $order['user_id'],
                    'type' => 'service',
                    'target_id' => $order['id'],
                    'target_title' => '购买了' . $service['name'] . '服务',
                    'amount' => -$order['amount'],
                    'createtime' => time()
                ]);
                Db::commit();
                echo $pay->success();
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                Log::error("服务订单支付回调处理失败: " . $e->getMessage());
                echo $pay->fail();
            }
        }
    }

    
}